<template>
    <div class="contener">
        <!-- 页面 -->
        <div class="page">
            <!-- 搜索 -->
            <transition
                @before-enter="_beforeEnter"
                @enter="_enter"
                @after-enter="_afterEnter"
                @before-leave="_beforeLeave"
                @leave="_leave"
                @after-leave="_afterLeave"
            >
                <div
                    class="search-contener"
                    ref="searchContener"
                    v-show="searchFormConfig.searchContenerShow"
                >
                    <base-form
                        :formItems="searchFormConfig.formItems"
                        :formData="searchFormConfig.formSubmit"
                        ref="searchForm"
                        @onButtonClick="searchBarButtonClick"
                    />
                </div>
            </transition>
            <!-- 表格 -->
            <div class="datas-contener">
                <!-- 表格操作项 -->
                <div class="option-contener">
                    <data-options
                        :leftConfig="buttonConfig.leftConfig"
                        @buttonClick="handelOptionClick"
                        ref="dataOption"
                    />
                </div>
                <!-- 表格展示项 -->
                <div class="table-contener">
                    <base-table
                        ref="baseTable"
                        :tableData="baseTableConfig.tableData"
                        :tableHeader="baseTableConfig.tableHeader"
                        :tableConfig="baseTableConfig.tableConfig"
                        :tree-props="
                            baseTableConfig.tableConfig.treeProps || undefined
                        "
                        @handleSelection="tableDataSelected"
                    >
                        <template slot-scope="{ scope }">
                            <el-switch
                                v-if="scope.type === 'switch'"
                                v-model="scope.row.status"
                                active-value="0"
                                inactive-value="1"
                                @change="switchStatus(scope.row)"
                            />
                            <div v-if="scope.type === 'handle'">
                                <el-button
                                    type="text"
                                    @click.stop="updateTableData(scope.row)"
                                    v-hasPermi="['tool/pserv/apiGroup/delete']"
                                    >修改</el-button
                                >
                                <el-button
                                    type="text"
                                    @click.stop="deleteTableData(scope.row)"
                                    v-hasPermi="['tool/pserv/apiGroup/delete']"
                                    >删除</el-button
                                >
                            </div>
                        </template>
                    </base-table>
                </div>
            </div>
        </div>
        <!-- 弹框 -->
        <el-dialog
            :title="dialogConfig.title"
            :visible.sync="dialogConfig.show"
            :width="dialogConfig.width"
            v-dialogDrag
            :close-on-click-modal="false"
            :close-on-press-escape="false"
            append-to-body
        >
            <!-- 筛选表格列 -->
            <div v-if="dialogConfig.key === 'tableColumn'">
                <base-transfer
                    :transferConfig="tableColumnTransferConfig"
                    ref="baseTransfer"
                />
            </div>
            <!-- 新增 -->
            <div v-if="dialogConfig.key === 'addTableData'">
                <base-form
                    :formItems="addFormConfig.formItems"
                    :formData="addFormConfig.formSubmit"
                    :formConfig="addFormConfig.formConfig"
                    :formRules="addFormConfig.formRule"
                    ref="addForm"
                    @onButtonClick="addFormButtonClick"
                />
            </div>
            <!-- 修改 -->
            <div v-if="dialogConfig.key === 'updateTableData'">
                <base-form
                    :formItems="updateFormConfig.formItems"
                    :formData="updateFormConfig.formSubmit"
                    :formConfig="updateFormConfig.formConfig"
                    :formRules="updateFormConfig.formRule"
                    ref="updateForm"
                    @onButtonClick="updateFormButtonClick"
                />
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button size="small" @click="handelCloseDialog"
                    >取 消</el-button
                >
                <el-button
                    size="small"
                    type="primary"
                    @click="handelCofimeDialog"
                    >确 定</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>
<script>
import BaseForm from '@/components/baseForm/index'
import DataOptions from '@/components/dataOptions/index'
import BaseTable from '@/components/baseTable/index'
import baseTransfer from '@/components/baseTransfer/index'
import globalMixin from '@/mixins/global'
import {
    apiGroupTree,
    apiGroupListAll,
    apiGroupSave,
    apiGroupDelete,
    apiGroupUpdate
} from '@/http/apis/tool/pserv/type'
import { getDictDatas } from '@/plugins/dict'
import {
    assemblyDataByTableColumn,
    setFormItemProp,
    handleTree
} from '@/utils/tool'
import { mapState } from 'vuex'
export default {
    components: {
        BaseForm,
        DataOptions,
        BaseTable,
        baseTransfer
    },
    computed: {
        ...mapState({
            deptInfo: state => state.dept.deptInfo
        })
    },
    mixins: [globalMixin],
    dicts: ['sys_normal_disable'],
    data() {
        return {
            // 通用树组件配置
            baseTreeConfig: {
                // tree的数据
                data: [],
                // tree的加载状态
                loading: false,
                // tree选中的树
                currentNodeKey: '',
                // 过滤显示
                filterShow: true
            },
            buttonConfig: {
                leftConfig: [
                    {
                        prop: 'addTableData',
                        label: '新增',
                        icon: 'el-icon-plus',
                        type: 'primary',
                        disabled: false,
                        hasPermi: ['tool/pserv/apiGroup/save']
                    },
                    {
                        prop: 'expandData',
                        label: '展开',
                        icon: 'el-icon-sort',
                        type: 'info',
                        disabled: false,
                        hasPermi: ['*']
                    }
                ]
            },
            // 搜索表单配置
            searchFormConfig: {
                formItems: [
                    [
                        {
                            ltype: 'input', // 大类型（input）
                            placeholder: '请输入分组名称', // 文字提示
                            label: '分组名称',
                            prop: 'groupName', // 绑定的key
                            width: 'w-auto'
                        },
                        {
                            ltype: 'select', // 大类型（input）
                            placeholder: '请选择状态', // 文字提示
                            label: '状态',
                            prop: 'status', // 绑定的key
                            width: 'w-auto',
                            options: getDictDatas('sys_normal_disable')
                        },
                        {
                            ltype: 'button', // 大类型（input）
                            type: 'primary',
                            text: '搜索', // 文字提示
                            prop: 'searchDatas', // 绑定的key
                            icon: 'el-icon-search',
                            width: 'w-auto',
                            loading: false
                        },
                        {
                            ltype: 'button', // 大类型（input）
                            type: 'default',
                            text: '重置', // 文字提示
                            prop: 'resetSearchForm', // 绑定的key
                            icon: 'el-icon-refresh-right',
                            width: 'w-auto'
                        }
                    ]
                ],
                formSubmit: {
                    groupName: '',
                    status: ''
                },
                formConfig: {
                    labelPosition: 'right', // label对齐方式
                    labelWidth: 'auto'
                },
                // 搜索控件是否显示
                searchContenerShow: true
            },
            // 表格配置
            baseTableConfig: {
                // 表格数据
                tableData: [],
                // 表格头数据
                tableHeader: [
                    {
                        prop: 'groupName',
                        label: '分组名称',
                        align: 'left',
                        visible: true
                    },
                    {
                        prop: 'sort',
                        label: '排序',
                        visible: true
                    },
                    {
                        prop: 'status',
                        type: 'switch',
                        label: '状态',
                        visible: true
                    },
                    {
                        prop: 'createTime',
                        label: '创建时间',
                        visible: true
                    },
                    {
                        prop: 'groupDesc',
                        label: '分组描述',
                        visible: true
                    },

                    {
                        label: '操作',
                        type: 'handle',
                        fixed: 'right',
                        visible: true
                    }
                ],
                // 表格配置
                tableConfig: {
                    loading: false,
                    rowKey: 'groupId',
                    //树的属性
                    treeProps: {
                        children: 'children',
                        hasChildren: 'hasChildren'
                    }
                },
                // 选中的表格数据
                tableCheckedDatas: []
            },
            // 弹框配置
            dialogConfig: {
                // 弹框标题
                title: '新增',
                // 是否显示
                show: false,
                // 宽度
                width: '30%',
                // 弹框标识(用来区分弹框内容)
                key: ''
            },
            // 查询表格数据的参数
            queryTableParams: {},
            // 表格列筛选配置
            tableColumnTransferConfig: {
                // 穿梭框的数据
                data: [],
                // 穿梭框的标题
                titles: ['显示', '隐藏'],
                // 隐藏的列
                modelList: []
            },
            // 新增表单配置
            addFormConfig: {
                // 表单项
                formItems: [
                    [
                        {
                            ltype: 'treeSelect',
                            placeholder: '选择上级分组',
                            label: '上级分组',
                            prop: 'parentId',
                            multiple: false,
                            options: []
                        }
                    ],
                    [
                        {
                            ltype: 'input',
                            placeholder: '请输入分组名称',
                            label: '分组名称',
                            prop: 'groupName',
                            width: 'w-1'
                        }
                    ],
                    [
                        {
                            ltype: 'inputNumber',
                            label: '显示排序',
                            prop: 'sort',
                            width: 'w-1',
                            min: 0
                        }
                    ],
                    [
                        {
                            ltype: 'select',
                            placeholder: '请选择状态',
                            label: '状态',
                            prop: 'status',
                            width: 'w-1',
                            options: getDictDatas('sys_normal_disable')
                        }
                    ],
                    [
                        {
                            ltype: 'input',
                            type: 'textarea',
                            placeholder: '请输入分组描述',
                            label: '分组描述',
                            prop: 'groupDesc',
                            width: 'w-1'
                        }
                    ]
                ],
                // 提交项
                formSubmit: {
                    parentId: null,
                    groupName: '',
                    sort: '0',
                    status: '',
                    groupDesc: ''
                },
                // 配置项
                formConfig: {
                    labelPosition: 'right', // label对齐方式
                    labelWidth: '80px'
                },
                // 验证项
                formRule: {
                    groupName: [
                        {
                            required: true,
                            message: '请输入部门名称',
                            trigger: 'blur'
                        }
                    ],
                    status: [
                        {
                            required: true,
                            message: '请选择用户状态',
                            trigger: 'blur'
                        }
                    ]
                }
            },
            // 修改表单配置
            updateFormConfig: {
                // 表单项
                formItems: [
                    [
                        {
                            ltype: 'treeSelect',
                            placeholder: '选择上级分组',
                            label: '上级分组',
                            prop: 'parentId',
                            multiple: false,
                            options: []
                        }
                    ],
                    [
                        {
                            ltype: 'input',
                            placeholder: '请输入分组名称',
                            label: '分组名称',
                            prop: 'groupName',
                            width: 'w-1'
                        }
                    ],
                    [
                        {
                            ltype: 'inputNumber',
                            label: '显示排序',
                            prop: 'sort',
                            width: 'w-1',
                            min: 0
                        }
                    ],
                    [
                        {
                            ltype: 'select',
                            placeholder: '请选择状态',
                            label: '状态',
                            prop: 'status',
                            width: 'w-1',
                            options: getDictDatas('sys_normal_disable')
                        }
                    ],
                    [
                        {
                            ltype: 'input',
                            type: 'textarea',
                            placeholder: '请输入分组描述',
                            label: '分组描述',
                            prop: 'groupDesc',
                            width: 'w-1'
                        }
                    ]
                ],
                // 提交项
                formSubmit: {},
                // 配置项
                formConfig: {
                    labelPosition: 'right', // label对齐方式
                    labelWidth: '80px'
                },
                // 验证项
                formRule: {
                    groupName: [
                        {
                            required: true,
                            message: '请输入分组名称',
                            trigger: 'blur'
                        }
                    ],
                    status: [
                        {
                            required: true,
                            message: '请选择用户状态',
                            trigger: 'blur'
                        }
                    ]
                }
            }
        }
    },
    created() {
        this.initPage()
    },
    methods: {
        /**
         * 页面开始
         */
        async initPage() {
            // 查询分组树列表
            await this.queryTree()
            // 设置表单的配置项
            this.setFormsItems()
            // 查询分组列表
            this.queryTableData(this.queryTableParams)
        },
        /**
         * 查询部门树
         */
        async queryTree() {
            this.baseTreeConfig.loading = true
            try {
                let res = await apiGroupTree()
                if (res && res.data) {
                    this.baseTreeConfig.data = res.data
                } else {
                    this.baseTreeConfig.data = []
                }
                this.baseTreeConfig.loading = false
            } catch (error) {
                this.baseTreeConfig.loading = false
            }
        },

        /**
         * 中间表格相关
         */

        /**
         * 查询表格数据
         */
        async queryTableData(params) {
            this.baseTableConfig.tableConfig.loading = true
            let res = await apiGroupListAll(params)
            if (res.data) {
                // 将数据转换成tree
                this.baseTableConfig.tableData = handleTree(
                    this.baseTableConfig.tableData.concat(res.data),
                    'groupId'
                )
            } else {
                this.baseTableConfig.tableData = []
            }
            this.baseTableConfig.tableConfig.loading = false
        },
        /**
         * 表格数据被选中
         */
        tableDataSelected(rows) {
            this.baseTableConfig.tableCheckedDatas = rows
        },
        /**
         * 初始化查询参数
         */
        initQueryParmas() {
            this.queryTableParams = {}
            this.baseTableConfig.tableData = []
        },

        /**
         * 搜索栏相关
         */
        /**
         * 搜索栏按钮点击
         * @param {Object} params
         */
        searchBarButtonClick(params) {
            // 清空查询参数
            this.initQueryParmas()
            try {
                this[params.prop]()
            } catch (error) {
                throw new Error(error)
            }
        },
        /**
         * 重置搜索表单
         */
        resetSearchForm() {
            // 查询参数初始化
            this.initQueryParmas()
            // 重置搜索表单
            this.$refs.searchForm.resetForm()
            // 查询数据
            this.refreshTableData()
        },

        /**
         * 搜索数据
         */
        searchDatas() {
            this.$refs.searchForm.submitForm(() => {
                // 清空查询参数
                this.initQueryParmas()
                // 组装查询条件
                this.queryTableParams = {
                    ...this.searchFormConfig.formSubmit
                }
                // 查询数据
                this.queryTableData(this.queryTableParams)
            })
        },

        /**
         * 操作栏相关
         */
        /**
         * 操作项点击
         * @param {*} params
         */
        handelOptionClick(params) {
            this[params] ? this[params]() : null
        },
        /**
         * 切换搜索栏的显示状态
         */
        switchSearchStatus() {
            this.searchFormConfig.searchContenerShow = !this.searchFormConfig
                .searchContenerShow
        },
        /**
         * 刷新表格数据
         */
        refreshTableData() {
            // 将当前表格数据设置为空
            this.baseTableConfig.tableData = []
            this.initPage()
        },
        /**
         * 设置表格显示隐藏列(打开弹框)
         */
        switchTableColumn() {
            let dialogParams = {
                title: '显示/隐藏',
                width: 'auto',
                show: true,
                key: 'tableColumn'
            }
            // 设置参与表格列控制的属性（最后的数组为不参与隐藏显示设置的列）
            this.tableColumnTransferConfig.data = assemblyDataByTableColumn(
                this.baseTableConfig.tableHeader,
                'label',
                ['选择', '分组名称', '操作']
            )
            this.handelOpenDialog(dialogParams)
        },
        /**
         * 设置表格显示隐藏列(弹框确认)
         */
        switchTableColumnButtonClick() {
            let newData = this.$refs.baseTransfer.backCheckedData()
            if (newData && newData.length > 0) {
                this.baseTableConfig.tableHeader.forEach(ele => {
                    ele.visible = !newData.includes(ele.label)
                })
            } else {
                this.baseTableConfig.tableHeader.forEach(ele => {
                    ele.visible = true
                })
            }
            this.handelCloseDialog()
        },
        /**
         * 设置(新增、修改)表单的表单项
         */
        async setFormsItems() {
            // 重新设置新增、修改 表单的部门树数据配置
            this.addFormConfig.formItems = setFormItemProp(
                this.addFormConfig.formItems,
                'parentId',
                'options',
                this.baseTreeConfig.data
            )
            this.updateFormConfig.formItems = setFormItemProp(
                this.updateFormConfig.formItems,
                'parentId',
                'options',
                this.baseTreeConfig.data
            )
        },
        /**
         * 新增表格数据(打开弹框)
         */
        addTableData() {
            // 打开新增弹框
            let dialogParams = {
                title: '新增',
                width: '40%',
                show: true,
                key: 'addTableData'
            }
            this.handelOpenDialog(dialogParams)
            this.$nextTick(() => {
                this.initAddForm()
            })
        },
        /**
         * 新增数据确认提交(弹框确认)
         */
        addFormButtonClick() {
            this.$refs['addForm'].submitForm(async res => {
                if (res) {
                    let assRes = await apiGroupSave(res)
                    if (assRes && assRes.code === 0) {
                        this.$message.closeAll()
                        this.$message.success({ message: '新增成功！' })
                        this.initAddForm()
                    } else {
                        this.$message.closeAll()
                        this.$message.error({ message: '新增失败！' })
                    }
                    this.handelCloseDialog()
                    // 查询数据
                    this.refreshTableData()
                }
            })
        },
        /**
         * 初始化新增表单
         */
        initAddForm() {
            this.addFormConfig.formSubmit = {
                parentId: null,
                groupName: '',
                sort: '0',
                status: '',
                groupDesc: ''
            }
            this.$refs.addForm.resetForm()
        },
        /**
         * 修改表格数据(打开弹框)
         */
        async updateTableData(row) {
            //如果是顶层部门，则默认没有值
            if (0 == row.parentId) {
                row.parentId = null
            }
            this.updateFormConfig.formSubmit = this.$_.cloneDeep(row)
            // 这里将后端返回的dept id 转换成 数组
            // this.updateFormConfig.formSubmit.deptId = [res.data.deptId]
            // 打开修改弹框
            let dialogParams = {
                title: '修改',
                width: '40%',
                show: true,
                key: 'updateTableData'
            }
            this.handelOpenDialog(dialogParams)
        },
        /**
         * 修改数据提交(弹框确认)
         */
        updateFormButtonClick() {
            this.$refs['updateForm'].submitForm(async res => {
                if (res) {
                    // 这里将控件选择后的数据转换为字符串
                    // res.deptId = res.deptId.toString()
                    let assRes = await apiGroupUpdate(res)
                    if (assRes && assRes.code === 0) {
                        this.$message.closeAll()
                        this.$message.success({ message: '修改成功！' })
                    } else {
                        this.$message.closeAll()
                        this.$message.error({ message: '修改失败！' })
                    }
                    this.handelCloseDialog()
                    // 查询数据
                    this.refreshTableData()
                }
            })
            this.initUpdateForm()
        },
        /**
         * 初始化修改表单
         */
        initUpdateForm() {
            this.updateFormConfig.formSubmit = {}
        },
        /**
         * 删除表格数据
         */
        deleteTableData(rows) {
            if (
                typeof rows === 'undefined' &&
                this.baseTableConfig.tableCheckedDatas.length > 0
            ) {
                rows = this.baseTableConfig.tableCheckedDatas
            }
            if (typeof rows !== 'undefined') {
                let params = []
                if (Array.isArray(rows) && rows.length) {
                    for (let i = 0; i < rows.length; i++) {
                        const element = rows[i]
                        params.push(element.groupId)
                    }
                } else {
                    params = [rows.groupId]
                }
                this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(async () => {
                        let res = await apiGroupDelete(params)
                        if (res && res.code == 0) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            })
                        } else {
                            this.$message({
                                type: 'error',
                                message: '删除失败!'
                            })
                        }
                        // 查询数据
                        this.refreshTableData()
                    })
                    .catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        })
                    })
            } else {
                this.$message({
                    type: 'error',
                    message: '请选择数据！'
                })
            }
        },
        /**
         * 修改数据的状态
         * @param {*} row
         */
        async switchStatus(row) {
            this.$confirm(
                `是否将该用户状态设置为${
                    row.status === '0' ? '启用' : '停用'
                }?`,
                '提示',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }
            )
                .then(async () => {
                    this.updateFormConfig.formSubmit = row
                    this.updateFormConfig.formSubmit.status = row.status
                    let assRes = await apiGroupUpdate(
                        this.updateFormConfig.formSubmit
                    )
                    if (assRes && assRes.code === 0) {
                        this.$message.closeAll()
                        this.$message.success({ message: '修改成功！' })
                    } else {
                        this.$message.closeAll()
                        this.$message.error({ message: '修改失败！' })
                    }
                    // 查询数据
                    this.refreshTableData()
                })
                .catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消修改'
                    })
                    // 查询数据
                    this.refreshTableData()
                })
        },

        /**
         * 弹框相关
         */
        /**
         * 打开弹框
         * @param {*} params
         */
        handelOpenDialog(params) {
            this.dialogConfig = params
        },
        /**
         * 初始化弹框
         */
        handelInitDialog() {
            this.dialogConfig = {
                title: '',
                show: false,
                width: '',
                key: ''
            }
        },
        /**
         * 关闭弹框
         */
        handelCloseDialog() {
            this.handelInitDialog()
        },
        /**
         * 弹框确定
         */
        handelCofimeDialog() {
            // 表格列筛选的弹框
            if (this.dialogConfig.key === 'tableColumn') {
                this.switchTableColumnButtonClick()
            } else if (this.dialogConfig.key === 'addTableData') {
                this.addFormButtonClick()
            } else if (this.dialogConfig.key === 'updateTableData') {
                this.updateFormButtonClick()
            }
        },

        //展开折叠
        expandData() {
            this.expandAll = !this.expandAll
            if (this.expandAll) {
                this.$refs.dataOption.updateButtonStatus(
                    'expandData',
                    'type',
                    'primary'
                )
                this.$refs.dataOption.updateButtonStatus(
                    'expandData',
                    'label',
                    '收起'
                )
            } else {
                this.$refs.dataOption.updateButtonStatus(
                    'expandData',
                    'type',
                    'info'
                )
                this.$refs.dataOption.updateButtonStatus(
                    'expandData',
                    'label',
                    '展开'
                )
            }
            this.$refs.baseTable.toggleRowExpansion()
        }
    }
}
</script>
<style lang="scss" scoped></style>
